<template>
    <view class="container" :style="themeColor">
        <view class="box">
            <!-- #ifdef MP -->
            <view class="login-wx">
                <view class="logo">
                    <image v-if="logo" class="logo-img" :src="easyGetImgUrl(logo)"></image>
                </view>
                <view class="titlename">{{ shopName }}</view>
                <view class="agreement" v-if="getAppSet().agreement">
                    <label class="agrlabel" @click="selectFn(agreementchecked)">
                        <iconsfont customIcons="icon-yuanquan" :color="$store.state.themeColor" size="32"
                            v-show="!agreementchecked"></iconsfont>
                        <iconsfont customIcons="icon-xuanzhong1" :color="$store.state.themeColor" size="32"
                            v-show="agreementchecked"></iconsfont>
                    </label>
                    <view class="color-dark" @click="selectFn(agreementchecked)">登录注册表示您已阅读并同意</view>
                    <view><text @click="agreement()">《用户协议》</text>和<text @click="privacy()">《隐私政策》</text></view>
                </view>
                <view v-if="getAppSet().agreement">
                    <button class="btn btn-success btn-save sqbtn" v-show="!agreementchecked" @click="noAgreement()">
                        手机号快捷登录
                    </button>
                    <button class="btn btn-success btn-save sqbtn" v-show="agreementchecked" open-type="getPhoneNumber"
                        @getphonenumber="decryptPhoneNumber">
                        手机号快捷登录
                    </button>
                </view>
                <view v-else>
                    <button class="btn btn-success btn-save sqbtn" open-type="getPhoneNumber"
                        @getphonenumber="decryptPhoneNumber">
                        手机号快捷登录
                    </button>
                </view>
                <!-- <view class="loginTwo" @click="easyGoTo('/pages/login/index')">账号密码登录/注册</view> -->
                <!-- <button class="btn btn-white btn-save zhbtn" @click="goaccountlogin">账号登录</button> -->
                <view :class="webInfo.IsVisitor && (!token || token == '') ? 'login-bottom' : 'login-bottom login-bottom-center'
                    ">
                    <view class="register-tip" @click="easyGoTo('/pages/login/index')">
                        <text>账号密码登录/注册</text>
                    </view>
                    <view class="tourist" v-if="webInfo.IsVisitor && (!token || token == '')" @click="touristFn">
                        <view class="yuan">
                            <iconsfont customIcons="icon-zuji" color="#fff" size="26"></iconsfont>
                        </view>游客登录
                    </view>
                </view>
                <uni-popup ref="bindmobile">
                    <view class="mobileall">
                        <view class="mobletxt">为了更好的体验,请授权手机号</view>
                        <view class="flex-s-s">
                            <button class="btn btn-gray btn-save mobilebtn" @click="closePopup">取消</button>
                            <button class="btn btn-success btn-save mobilebtn" open-type="getPhoneNumber"
                                @getphonenumber="decryptPhoneNumber">
                                授权
                            </button>
                        </view>
                    </view>
                </uni-popup>
            </view>
            <!-- #endif -->
        </view>
        <web-view class="webView" v-if="isShow" ref="webView" :src="url">
            <cover-view class="webView-mark" v-if="isShow && showNav"> </cover-view>
        </web-view>
        <uni-popup ref="popTipApply" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="您当前位置暂时无法注册本平台\n是否申请注册" :before-close="true"
                @close="closeFn('popTipApply')" @confirm="applyFn" confirmText="申请"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyResult" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="申请成功,请耐心等待平台审核" :before-close="true" :showCancel="false"
                @confirm="closeFn('popTipApplyResult')"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyOK" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="您已注册,请耐心等待平台审核" :before-close="true" :showCancel="false"
                @confirm="closeFn('popTipApplyOK')" confirmText="确定"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="popTipApplyAgain" type="dialog">
            <uni-popup-dialog type="text" title="温馨提示" content="平台审核已拒绝您的注册申请" :before-close="true"
                @close="closeFn('popTipApplyAgain')" @confirm="applyAgainFn" cancelText="确定" confirmText="重新申请">
            </uni-popup-dialog>
        </uni-popup>
        <privacy-agreement></privacy-agreement>
        <!--#ifdef APP-->
        <view class="bei-an" v-if="webInfo.AppIcpNo">{{ webInfo.AppIcpNo }}</view>
        <!--#endif-->
        <!--#ifndef APP-->
        <view class="bei-an" v-if="webInfo.MiniAppIcpNo">{{ webInfo.MiniAppIcpNo }}</view>
        <!--#endif-->
    </view>
</template>

<script>
import { mapMutations, mapState } from "vuex"
import cardCellInput from "@/components/common/cell/card-cell-input.vue"
import privacyAgreement from "@/components/privacy-agreement/privacy-agreement.vue"
import { getUserInfo, getProductDisplay } from "@/utils/appInit.js"
import storage from "@/uni-sub-base/utils/storage.js"
import { getUserCarList } from "@/utils/cartUtil.js"
import config from "@/config/config.js"
import { mobileLogin } from "@/service/api/user.js"
import { getMiniProgramOpenId, AESDecrypt, GetMiniAppPhone, MiniAppOAuthLogin } from "@/service/api/weChat.js"
import { registerByWeixin, RegisterAndLogin } from "@/service/api/authorize.js"
import { AddLoginAuthApply } from "@/service/api/loginAuth.js"
import { judgeIsExist } from "@/service/api/member.js"
import webViewUrl from "@/pages/micro/webViewUrl.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
export default {
    components: {
        cardCellInput,
        privacyAgreement
    },
    data() {
        return {
            code: "", // 绑定手机号需要的code
            phoneCode: "",
            agreementchecked: false,
            logo: "",
            loginBg: "",
            sessionKey: "",
            openId: "",
            nickName: null,
            avatarUrl: null,
            userInfo: {},
            data: "",
            isShow: false,
            url: "",
            showNav: false,
            location: null,
            userData: null,
            shopName: "",
            token: null,
            webInfo: {}
        }
    },
    onLoad(e) { },
    onShow() {
        this.getWebInfo()

        const accountInfo = uni.getAccountInfoSync();
        console.log("accountInfo", accountInfo)
    },
    mounted() {
        console.log("mounted", this.getAppSet())
        this.shopName = this.getAppSet().shopName
        this.getLocation()
    },
    methods: {
        ...mapMutations(["SET_AUTH"]),
        getWebInfo() {
            let webInfo = storage.getCache("webInfo")
            this.webInfo = webInfo
            if (webInfo) {
                this.logo = webInfo.Logo
                this.loginBg = webInfo.LoginBackgroud
                this.canRegister = webInfo.AllowRegister
            } else {
                setTimeout((e) => {
                    this.getWebInfo()
                    this.$forceUpdate()
                }, 1000)
            }
        },
        selectFn(vaule) {
            this.agreementchecked = !this.agreementchecked
        },
        agreement() {
            // this.easyGoTo("/pages/web/h5?url=" + encodeURIComponent(this.getAppSet().agreementUrl))
            this.easyGoTo("/pages/web/agreement?type=4")
        },
        privacy() {
            // this.easyGoTo("/pages/web/h5?url=" + encodeURIComponent(this.getAppSet().privacyUrl))
            this.easyGoTo("/pages/web/agreement?type=5")
        },
        authorizeFn() {
            // if(!this.agreementchecked && this.getAppSet().agreement==true){
            //     this.easyToast('请先同意《用户协议》和《隐私政策》')
            //     return;
            // }
            // this.$refs.bindmobile.open()
            uni.getUserProfile({
                desc: "登录",
                success: (res) => {
                    this.userData = res
                    this.data = JSON.stringify(res)
                    this.getLocation()
                },
                fail: (res) => {
                    console.log(res)
                },
            })
        },
        closePopup() {
            this.$refs.bindmobile.close()
        },
        //获取位置
        getLocationFn() {
            uni.getLocation({
                type: "wgs84",
                success: (res) => {
                    this.location = res
                    this.login()
                },
            })
        },
        //登录
        login() {
            let that = this
            // 获取登录用户code
            uni.login({
                provider: "weixin",
                success: function (res) {
                    if (res.code) {
                        let code = res.code
                        that.code = res.code
                        that.getOpenApi(res)
                    } else {
                        uni.showToast({
                            title: "登录失败！",
                            duration: 2000,
                        })
                    }
                },
            })
        },
        saveUserInfo(data) {
            storage.setCache("userInfo", data)
        },
        showLoginLoadding() {
            uni.showLoading({
                title: "登录中",
            })
        },
        //微信登录接口
        getOpenApi(data) {
            // this.showLoginLoadding()
            let webInfo = storage.getCache("webInfo")
            let param = {
                code: data.code,
                businessId: webInfo.BusinessId,
                accId: webInfo.WxAccountId,
            }
            let path = "?code=" + data.code
            getMiniProgramOpenId(param, path).then((res) => {
                if (res.Data) {
                    // this.loginByApi(res.Data)
                    let open_id = res.Data.OpenId
                    let union_id = res.Data.UnionId || ""
                    storage.setCache("openId", open_id)
                    storage.setCache("unionId", union_id)
                }
            })
        },
        //微信登录接口
        loginByApi(data) {
            let open_id = data.OpenId
            let union_id = data.UnionId || ""
            storage.setCache("openId", open_id)
            storage.setCache("unionId", union_id)
            let param = {
                open_id: open_id,
                union_id: union_id,
            }
            let lng = this.location.longitude
            let lat = this.location.latitude
            let province = this.location.address.province
            let city = this.location.address.city
            let area = this.location.address.district
            let face = this.userData.userInfo.avatarUrl
            let nick_name = this.userData.userInfo.nickName
            let path = `?open_id=${open_id}&union_id=${union_id}&nick_name=${nick_name}&face=${face}&province=${province}&city=${city}&area=${area}&lat=${lat}&lng=${lng}`
            RegisterAndLogin(param, path).then((res) => {
                uni.hideLoading()
                if (res.State == 1 && res.Data) {
                    let data = res.Data
                    this.userId = data.UserId
                    if (data.State == 0 && data.Token) {
                        //0表示正常(启用)
                        // this.goHome(data.Token)
                        // 打开授权手机号
                        this.token = data.Token
                        this.$refs.bindmobile.open()
                    } else if (data.ApplyedLogin) {
                        //表示是否已经有了待审核的登录授权申请
                        this.$refs.popTipApplyOK.open()
                    } else if (data.State == 5) {
                        //5表示登录受限
                        this.$refs.popTipApply.open()
                    }
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        applyFn() {
            let webInfo = storage.getCache("webInfo")
            this.closeFn("popTipApply")
            //请求接口
            let param = {
                applyMessage: "申请",
                businessId: webInfo.BusinessId,
                userId: this.userId,
            }
            AddLoginAuthApply(param).then((res) => {
                if (res.State == 1) {
                    this.$refs.popTipApplyResult.open()
                }
            })
        },
        applyAgainFn() {
            this.closeFn("popTipApplyAgain")
            this.$refs.popTipApplyOK.open()
        },
        closeFn(type) {
            if (type == "popTipApplyResult") {
                this.$refs.popTipApplyResult.close()
            } else if (type == "popTipApply") {
                this.$refs.popTipApply.close()
            } else if (type == "popTipApplyOK") {
                this.$refs.popTipApplyOK.close()
            } else if (type == "popTipApplyAgain") {
                this.$refs.popTipApplyAgain.close()
            }
        },
        getLocation() {
            getLocation(
                (res) => {
                    if (res) {
                        this.location = res
                        this.login()
                    }
                },
                (error) => { },
            )
        },
        noAgreement() {
            if (!this.agreementchecked && this.getAppSet().agreement == true) {
                this.easyToast("请先同意《用户协议》和《隐私政策》")
                return
            }
        },
        //授权手机号
        decryptPhoneNumber(e) {
            let that = this
            // 参数e是绑定的授权方法自动传入过来的,
            //主要是为了拿到vi和encryptedData值从后台换取用户联系方式
            if ("getPhoneNumber:ok" != e.detail.errMsg) {
                let url = "/pages/login/loading"
                uni.reLaunch({
                    url: url,
                })
                return
            }
            let iv = e.detail.iv
            let encryptedData = e.detail.encryptedData
            let code = that.code
            that.phoneCode = e.detail.code
            //调用后台接口获取用户手机号码
            let path = "?code=" + e.detail.code
            GetMiniAppPhone(path).then((res) => {
                if (res.State == 1) {
                    that.phone = res.Data.Phone
                    that.judgeIsExist(that.phone)
                } else {
                    that.easyToast(res.Msg)
                }
            })
        },
        judgeIsExist(tel) {
            let that = this
            judgeIsExist(tel).then((res) => {
                if (res.State == 1) {
                    that.easyGoTo("/pages/login/register?phone=" + that.phone)
                } else {
                    if (res.Msg == "用户已存在") {
                        that.showLoginLoadding()
                        that.goLogin()
                    } else {
                        that.easyToast(res.Msg)
                    }
                }
            })
        },
        goLogin() {
            MiniAppOAuthLogin({ phoneCode: this.phoneCode }).then((res) => {
                if (res.State == 1) {
                    if (res.Data.State == 0) {
                        let token = res.Data.Token
                        this.goHome(token)
                    } else if (res.Data.State == 1) {
                        uni.hideLoading()
                        this.easyToast("您已提交注册申请，等待审核中")
                    } else {
                        uni.hideLoading()
                        this.easyToast(res.Data.StateName)
                    }
                } else {
                    uni.hideLoading()
                    this.easyToast(res.Msg)
                }
            })
        },
        goHome(token) {
            this.SET_AUTH(token)
            //#ifdef APP-PLUS
            if (getPlatform() == "ios") {
                let webInfo = storage.getCache("webInfo")
                if (webInfo) {
                    this.url =
                        webInfo.WebDomain +
                        (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                        "?uniToken=" +
                        token
                }
                this.isShow = true
                setTimeout((e) => {
                    this.getUserInfo()
                }, 2500)
                getUserCarList()
                getProductDisplay().then((res) => { })
            } else {
                this.isShow = true
                setTimeout((e) => {
                    this.getUserInfo()
                }, 4500)
                getUserCarList()
                getProductDisplay().then((res) => { })
            }
            //#endif
            //#ifndef APP-PLUS
            let webInfo = storage.getCache("webInfo")
            if (webInfo) {
                this.url =
                    webInfo.WebDomain +
                    (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                    "?uniToken=" +
                    token
            }
            // this.isShow = true

            setTimeout((e) => {
                this.getUserInfo()
            }, 2500)
            getUserCarList()
            getProductDisplay().then((res) => { })
            //#endif
        },
        getUserInfo() {
            let url = "/pages/index/index"
            getUserInfo().then((res) => {
                uni.hideLoading()
                uni.reLaunch({
                    url: url,
                })
            })
        },
        touristFn() {
            let token = storage.getCache("token")
            let webInfo = storage.getCache("webInfo")
            if (webInfo.IsVisitor && (!token || token == "")) {
                //有游客账号
                uni.reLaunch({
                    url: "/pages/index/index",
                })
            } else {
                this.easyToast("后台未开启游客模式")
            }
        },
    },
}
</script>

<style lang="scss">
page {
    background: $color-white;
}

.container {
    padding: 300rpx 60rpx 200rpx;
}

.login-wx {
    .business {
        display: flex;
        justify-content: center;
        border-bottom: solid 1rpx #cdcdcd;
        margin-bottom: 48rpx;
        padding-bottom: 48rpx;

        text {
            font-size: $font-size-44;
        }
    }

    .apply-tip {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .apply-tip-title {
            color: $color-black;
            font-size: $font-size-32;
            margin-bottom: 36rpx;
        }

        .apply-tip-desc {
            color: $app-color-text-desc;
            font-size: $font-size-26;
        }

        margin-bottom: 80rpx;
    }

    .btn {
        height: 80rpx;
        border-radius: 100rpx;
    }
}

.webView-mark {
    width: 100vw;
    height: 100vh;
    background: #fff;
    position: fixed;
    z-index: 999999999999;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
}

.webView-mark-load-text {
    margin-top: 300rpx;
}

.agreement {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0rpx -60rpx 38rpx -60rpx;

    .circle {
        width: 28rpx;
        height: 28rpx;
        border-radius: 50%;
        border: 1rpx solid #999;
        display: block;
        overflow: hidden;
    }

    .agrlabel {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    view {
        font-size: 24rpx;

        text {
            color: $app-color-main !important;
        }
    }

    .color-dark {
        padding-left: 8rpx;
    }
}

.logo {
    display: flex;
    justify-content: center;
    height: 140rpx;
    margin-bottom: 28rpx;

    .logo-img {
        width: 140rpx;
        height: 140rpx;
        border-radius: 40rpx;
        box-shadow: 0rpx 0rpx 30rpx rgba($color-black, 0.1);
    }
}

.titlename {
    font-size: 40rpx;
    font-weight: bold;
    color: #333333;
    text-align: center;
    padding-bottom: 128rpx;
}

.sqbtn {
    font-size: 30rpx;
}

.zhbtn {
    margin-top: 30rpx;
    font-size: 30rpx;
}

.mobileall {
    background: white;
    padding: 30rpx;
    width: 500rpx;
    height: 200rpx;
    border-radius: 20rpx;
    position: relative;
    z-index: 1;

    .mobletxt {
        text-align: center;
        margin: 30rpx 0;
        font-size: 24rpx;
    }

    .icon-close {
        position: absolute;
        top: $app-page-padding;
        right: $app-page-padding;
        z-index: 22;
    }

    .mobilebtn {
        width: 200rpx !important;
    }
}

.loginTwo {
    color: #666;
    text-align: center;
    font-size: 30rpx;
    margin-top: 32rpx;
}

.bei-an {
    position: fixed;
    bottom: 24rpx;
    text-align: center;
    width: 100%;
    left: 0;
}


.login-bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 40rpx;

    .register-tip {
        display: flex;
        justify-content: center;

        text {
            font-size: 28rpx;
        }

        .link-text {
            color: $app-color-main;
        }
    }

    .tourist {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #999;

        .yuan {
            width: 38rpx;
            height: 38rpx;
            background: #fdb52a;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 20rpx;
            margin-right: 16rpx;
        }
    }
}

.login-bottom-center {
    justify-content: center;
}
</style>
